package com.cqupt.service.impl;


import com.cqupt.mapper.EnclosureMapper;
import com.cqupt.mapper.KnowledgeBaseMapper;
import com.cqupt.pojo.Enclosure;
import com.cqupt.pojo.Knowledge;
import com.cqupt.pojo.Type;
import com.cqupt.service.KnowledgeService;
import com.cqupt.utils.DateUtils;
import com.cqupt.utils.KnowledgeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class KnowledgeServiceImpl implements KnowledgeService {

    @Autowired
    private KnowledgeBaseMapper konwladgeMapper;
    @Autowired
    private EnclosureMapper enclosureMapper;

    /**
     * 查询所有知识（加筛选）
     *
     * @param typeid         知识类别id
     * @param view_type      最热或最新
     * @param approvalStatus 审批状态
     * @param searchText     关键字
     * @return
     */
    public List<Map<String, Object>> getAllKnowledge(int typeid, int view_type, int approvalStatus, String searchText) {
        return konwladgeMapper.getAllKnowledge(typeid, view_type, approvalStatus, searchText);
    }

    // 新增知识(返回主键)
    public Integer insertKnowledge(Knowledge knowledge) {
        konwladgeMapper.insertKnowledge(knowledge);
        return knowledge.getId();
    }

    // 删除知识
    public Integer deleteKnowledge(int id) {
        return konwladgeMapper.deleteKnowledge(id);
    }

    // 修改知识
    public Integer updateKnowledge(Knowledge knowledge) {
        return konwladgeMapper.updateKnowledge(knowledge);
    }

    // 根据id查询知识
    public Map<String, Object> getKnowledgeById(int id) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("knowledge", konwladgeMapper.getKnowledgeById(id));
        resultMap.put("closure", enclosureMapper.getEnclosureById(id));
        return resultMap;
    }

    /**
     * 采纳知识
     *
     * @param id        知识id
     * @param commonKey 公共键值
     * @return
     */
    @Override
    public Integer adoptKnowledge(int id, String commonKey) {
        Map<String, Object> resMap = konwladgeMapper.findRelationshipKK(id, commonKey);
        System.out.println("打印：" + resMap);
        int count = ((Number) resMap.get("count")).intValue();
        Integer flag = -1;
        if (count == 0) {
            // 若 count为0，则创建绑定
            flag = konwladgeMapper.insertRelationship(id, commonKey);
        } else {
            int newCount = ((Number) resMap.get("adoptCount")).intValue() + 1;
            flag = konwladgeMapper.adoptAddOne(id, commonKey, newCount);
        }
        return flag;
    }

    /**
     * 以树形结构，返回所有的分类
     *
     * @param map 包含type、pagenum、pagesize参数的集合
     * @return 数据库中所有的分类
     */
    @Override
    public List<Type> getAllType(Map<String, Object> map) {
        int level = (int) map.get("type") - 1;
        // 调用工具类中 transformData 方法，以树形结构返回类型
        List<Type> types = KnowledgeUtils.transformData(konwladgeMapper.getAllType(), 0, level);
        if (map.get("pagenum") == null) return types;
        int size = (int) map.get("pagesize");
        int s = ((int) map.get("pagenum") - 1) * size;
        int e = Math.min(s + size, types.size());
        return types.subList(s, e);
    }

    /**
     * 获取所有的分类总数
     *
     * @return 分类总数
     */
    @Override
    public Integer getAllTypeCount() {
        return konwladgeMapper.getAllTypeCount();
    }

    /**
     * 添加分类
     *
     * @param t 类型对象
     * @return 是否添加成功
     */
    @Override
    public Integer addType(Type t) {
        return konwladgeMapper.addType(t);
    }

    /**
     * 删除分类，及其子分类
     *
     * @param ids 要被删除的id 和子类型的id
     * @return
     */
    @Override
    public Integer deleteTypeById(List<Integer> ids) {
        // 如果该分类或子分类下有知识，那么不允许删除
        Integer count = konwladgeMapper.getKnowledgeCountByType(ids);
        if (count > 0) return -1;
        return konwladgeMapper.deleteTypeById(ids);
    }

    /**
     * 更新分类
     *
     * @param t 分类对象
     * @return 是否更新成功
     */
    @Override
    public Integer updateType(Type t) {
        return konwladgeMapper.updateType(t);
    }

    @Override
    public Integer getKnowledgeCountByType(List<Integer> ids) {
        return konwladgeMapper.getKnowledgeCountByType(ids);
    }

    /**
     * 根据类别id获取种类名称
     *
     * @param id 知识id
     * @return
     */
    @Override
    public String getTypeNameByID(int id) {

        return konwladgeMapper.getTypeById(id);
    }

    /**
     * 根据公共键值返回知识列表
     *
     * @param after_exp 公共键值
     * @return
     */
    @Override
    public List<Map<String, Object>> findKnowledgeByKey(String after_exp) {
        List<Map<String, Object>> allCommonkey = konwladgeMapper.getAllCommonkey();
        String[] expression = after_exp.split("\\|");
        float exp_len = expression.length;
        for (int j = 0; j < allCommonkey.size(); j++) {
            String[] sub_commonkey = allCommonkey.get(j).get("common_key").toString().split("\\|");
            //System.out.println("sub_commonkey:" + Arrays.asList(sub_commonkey));
            float count = DateUtils.getAllSameElement(expression, sub_commonkey);
            float sub_coommon_len = sub_commonkey.length;
            //System.out.println("count:"+count);
            allCommonkey.get(j).put("len_similarity", Math.abs(exp_len - sub_coommon_len) / exp_len);
            allCommonkey.get(j).put("grade", (count / exp_len) * 100);
        }
        // 对分数进行排序
        Collections.sort(allCommonkey, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                Integer age1 = Math.round((Float) o1.get("len_similarity"));
                Integer age2 = Math.round((Float) o2.get("len_similarity"));
                return age1.compareTo(age2);//升序
            }
        });
        // 对分数进行排序
        Collections.sort(allCommonkey, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                Integer age1 = Math.round((Float) o1.get("grade"));
                Integer age2 = Math.round((Float) o2.get("grade"));
                return age2.compareTo(age1);//降序
            }
        });
        //System.out.println("allCommonkey:"+allCommonkey);
        // 封装到ids列表中
        List<String> ids = new ArrayList<>();
        for (int i = 0; i < allCommonkey.size(); i++) {
            //System.out.println("grade:"+allCommonkey.get(i).get("grade"));
            if ((float) allCommonkey.get(i).get("grade") != 0.0) {
                String[] knowledgeIDs = allCommonkey.get(i).get("knowledgeID").toString().split("\\,");
                for (int j = 0; j < knowledgeIDs.length; j++) {
                    ids.add(knowledgeIDs[j]);
                }
            }
        }
        //System.out.println(ids);
        if (ids.size() != 0) {
            // 按需查找知识
            return konwladgeMapper.findKnowledgeByidAndOrder(ids);
        } else {
            return null;
        }
    }

    /**
     * @param id           知识id
     * @param approval     审批状态
     * @param approval_man 审批者
     * @return
     */
    @Override
    public boolean approvalKnowledge(int id, int approval, String approval_man) {
        if (approval == 1) {
            if (konwladgeMapper.approvalKnowledgeByID(id, approval_man) > 0) {
                return true;
            } else {
                return false;
            }
        } else {
            if (konwladgeMapper.approvalRefuseKnowledgeByID(id, approval_man) > 0) {
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * 查询已绑定的知识列表
     *
     * @param after_exp 公共键值
     * @return
     */
    @Override
    public List<Map<String, Object>> findBoundedKnowledgeBounded(String after_exp) {
        // 查询数据库
        List<Integer> idList = konwladgeMapper.findBoundedKonwledges(after_exp);
        //System.out.println(idList.size());
        List<Map<String, Object>> knowledgeList;
        if (idList.size() != 0) {
            // 根据list查询知识具体信息
            knowledgeList = konwladgeMapper.findBoundedKonwledgesDetails(idList);
        } else {
            knowledgeList = null;
        }

        return knowledgeList;
    }

    /**
     * 设置浏览次数
     *
     * @param knowledgeId 知识id
     * @return
     */
    @Override
    public int setKnowledgeViewCount(int knowledgeId) {
        int flag = konwladgeMapper.addKnowledgeViewCount(knowledgeId);
        return flag;
    }

    @Override
    public List<Enclosure> getClosureByKnowledgeId(Map<String, Object> params) {
        return konwladgeMapper.getClosureByKnowledgeId(params);
    }
}
